using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Compilation;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;

public class GeneratorUIEditor : EditorWindow
{

    public string outPath = "";
    public string defaultPath = "/Scripts/UI/AutoGenerate";
    GameObject prefab;
    string nameSpace = "";
    bool is_item = false;

    void OnEnable()
    {

    }

    private void OnGUI()
    {
        GUILayout.Label("UINewFile", EditorStyles.boldLabel);


        //横向布局
        EditorGUILayout.BeginHorizontal();
        // if(outPath == "")
        // {
        //     outPath = Application.dataPath + defaultPath;
        // }

        // outPath = EditorGUILayout.TextField("输出路径", outPath);
        // //button
        // if(GUILayout.Button("Set OutPath"))
        // {   
        //     //设置输出路径
        //     outPath = EditorUtility.OpenFolderPanel("Select OutPath", outPath, "");
        //     Debug.Log(outPath);
        //     if(outPath == "")
        //     {
        //         outPath = Application.dataPath + defaultPath;
        //     }

        // }

        EditorGUILayout.EndHorizontal();

        //gameobject field
        prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", prefab, typeof(GameObject), false);
        nameSpace = EditorGUILayout.TextField("NameSpace", nameSpace);

        EditorGUILayout.LabelField("是否是Item 如果是Item则会生成一个Item类 在输出目录下生成文件 不会像UI类一样生成一个文件夹");
        is_item = EditorGUILayout.Toggle("Is Item", is_item);


        //button
        if(GUILayout.Button("Create UI File"))
        {   
            if(prefab == null)
            {
                Debug.LogError("prefab is null");
                return;
            }
            string prefabPath = AssetDatabase.GetAssetPath(prefab);
            var pathMgr = EditorPathMgr.Instance;
            if(!prefabPath.Contains(pathMgr.UIPrefabRootPath))
            {
                // Debug.LogError("prefab is not in Prefab folder");
                EditorUtility.DisplayDialog("Error", $"prefab不在{pathMgr.UIPrefabRootPath}目录下", "OK");
                return;
            }
            // CreateUIFile();
            var prefabSubPath = prefabPath.Replace(pathMgr.UIPrefabRootPath + "/","");
            Debug.Log(prefabSubPath);
            var codePath = "";
            if(prefabSubPath.Contains("/"))
            {
                var arr = prefabSubPath.Split('/');
                var subPath = arr[0];
                codePath = pathMgr.UICodeRootPath + "/" + subPath + "/UI";
            }else{
                codePath = pathMgr.UICodeRootPath + "/Common/UI";
            }

            UIGeneratorMgr.Instance.GeneratorUICode(prefab, prefab.name, codePath , nameSpace, is_item);
        }


        //button
        if(GUILayout.Button("Add Component"))
        {   
            if(prefab == null)
            {
                Debug.LogError("prefab is null");
                return;
            }
            // AddComponent();
            UIGeneratorMgr.Instance.AddComponent(prefab, prefab.name,nameSpace, is_item);
        }

        //button
        if(GUILayout.Button("Remove Component"))
        {   
            if(prefab == null)
            {
                Debug.LogError("prefab is null");
                return;
            }
            // AddComponent();
            UIGeneratorMgr.Instance.RemoveComps(prefab,nameSpace,is_item);
        }

        if(GUILayout.Button("test"))
        {   
            // if(prefab == null)
            // {
            //     Debug.LogError("prefab is null");
            //     return;
            // }
            // UIGeneratorMgr.Instance.GenteratorConfig(prefab.name,is_item);
            // var configPath = "Assets/Scripts/Config/UI/UIConfig.asset";
            // var data = AssetDatabase.LoadAssetAtPath<UIEditorItem>(configPath);
            // data.Name = UINAMES.UITEST1;
            // EditorUtility.SetDirty(data);
        }

        if(GUILayout.Button("生成所有UI配置"))
        {   
            // get all ui prefab
            var guids = AssetDatabase.FindAssets("t:Prefab", new string[]{"Assets/Prefab"});
            List<UIEditorItem> list = new List<UIEditorItem>();
            foreach(var guid in guids)
            {
                var path = AssetDatabase.GUIDToAssetPath(guid);
                var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
                if(prefab.GetComponent<UIBase>() != null)
                {
                    var dir = EditorPathMgr.Instance.UIEditorCfgPath;
                    var file = dir + "/" + prefab.name + ".asset";
                    // assetdatabase load asset
                    var data = AssetDatabase.LoadAssetAtPath<UIEditorItem>(file);
                    if(data == null)
                    {
                        data = ScriptableObject.CreateInstance<UIEditorItem>();
                        data.Name = GetUIName(prefab.name);
                        data.Prefab = prefab;
                        AssetDatabase.CreateAsset(data, file);
                    }else{
                        data.Name = GetUIName(prefab.name);
                        data.Prefab = prefab;
                        EditorUtility.SetDirty(data);
                    }
                    list.Add(data);
                }
            }
            Debug.Log("list count:" + list.Count);
            var filePath = "Assets/Scripts/UI/UIConfig.asset";
            var config = AssetDatabase.LoadAssetAtPath<UIConfig>(filePath);
            if(config == null)
            {
                config = ScriptableObject.CreateInstance<UIConfig>();
                AssetDatabase.CreateAsset(config, filePath);
            }
            if(config.Dic == null)
            {
                config.Dic = new List<UIItemCfg>();
            }
            config.Dic.Clear();
            foreach (var item in list)
            {
                var data = new UIItemCfg();
                data.Name = item.Name;
                string path = AssetDatabase.GetAssetPath(item.Prefab);
                data.Prefab = path;
                data.Layer = item.Layer;
                data.FullScreen = item.FullScreen;
                config.Dic.Add(data);
            }
            EditorUtility.SetDirty(config);
            // AssetDatabase.SaveAssets();
            // AssetDatabase.Refresh();
        }

        if (GUILayout.Button("强制编译"))
        {
            // Export();
            // RemoveAssets();
            CompilationPipeline.RequestScriptCompilation();
        }

    }

    UINAMES GetUIName(string name)
    {
        var tmp = name.ToUpper();
        foreach(var item in System.Enum.GetValues(typeof(UINAMES)))
        {
            if(tmp == item.ToString())
            {
                return (UINAMES)item;
            }
        }
        return UINAMES.NONE;
    }
}